<template>
  <div>
    <div class="top">
      <van-icon name="arrow-left" @click="goback"/>
      <van-search
        v-model="value"
        placeholder="请输入搜索关键词"
        @input="onSearch"
      />
    </div>
    <div class="his">
       <div class="item-name">搜索历史</div>
      <div class="item" v-for="val in historyList">
        {{val}}
      </div>
    </div>
    <!-- 搜索内容的下拉展示 -->
    <div class="content" v-if="value.length" >
      <h4>搜索的关键词是{{ value }}</h4>
      <template v-for="item in resultList">
        <p @click="close(item.name)">{{ item.name }}</p>
      </template>
    </div>
  </div>
</template>
<script>
import Vue from "vue";
import { Icon, Search } from "vant";
import { IndexBar, IndexAnchor, Cell } from "vant";
import {mapGetters} from 'vuex'
Vue.use(Search);
Vue.use(Icon);
Vue.use(IndexBar);
Vue.use(IndexAnchor);
export default {
  data() {
    return {
      value: "",
      resultList: [],
    };
  },
  computed:{
    ...mapGetters(['historyList']),
  },
  mounted() {
    this.$bus.$emit('hideMenu',false);
    this.gethistory();
  },
  beforeDestroy(){
    this.$bus.$emit('hideMenu',true);
  },
  methods: {
    // 根据关键词查找符合要求的信息
    async onSearch(val) {
      this.resultList = [];
      if (this.trim(val)) {
        let res = await this.$api.getkey(val);
        for (var attr in res.result) {
          if (attr !== "order") {
            this.resultList.push(...res.result[attr]);
          }
        }
      }
    },
    trim(str) {
      //删除左右两端的空格
      return str.replace(/(^\s*)|(\s*$)/g, "");
    },
    goback(){
      this.$router.go(-1);
    },
    addhistory(val){
      this.$store.commit('updateHistory',val);
      this.value="";
    },
    gethistory() {
      this.$store.commit('getHistory');
    },
    close(val){
      this.value="";
      this.addhistory(val);
    }
  },
};
</script>

<style scoped lang="scss">
/deep/ .top {
  display: flex;
  justify-content: space-around;
  align-items: center;
}
/deep/ .van-search {
  width: 80%;
}
/deep/ .van-icon {
  font-size: 25px;
}
.content {
  box-sizing: border-box;
  background: #fff;
  width: 100%;
  position: absolute;
  left: 0;
  top: 54px;
  padding: 15px;
  z-index: 2;
}
h4 {
  margin-bottom: 5px;
}
.content p {
  overflow:hidden;
  height: 30px;
  line-height: 30px;
  font-size: 16px;
  padding: 5px 0;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
}
.his {
  width:100%;
  height:30px;
  line-height:20px;
  display:flex;
  flex-wrap:wrap;
  align-items: flex-start;
}
.his .item,.item-name{
  padding:5px;
  text-align: center;
  border-radius: 5px;
  font-size: 10px;
  color:#333;
  margin-right: 5px;
}
.his .item {
   background: #ddd;
   border-radius: 10px;
}
</style>
